// useComponentExpose.ts
import { ref, onMounted, reactive, watch } from 'vue'

export function useComponentExpose<T extends object>(customMethods?: Record<string, Function>) {
    const componentRef = ref<T>()
    const exposeMethods = ref<Record<string, Function>>({})
    const exposed = reactive<Record<string, Function>>({})

    onMounted(() => {
        if (!componentRef.value) return

        for (const key in componentRef.value) {
            if (typeof (componentRef.value as any)[key] === 'function') {
                exposeMethods.value[key] = (...args: any[]) => {
                    return (componentRef.value as any)[key](...args)
                }
            }
        }
    })
    // 合并方法
    watch([exposeMethods], () => {
        Object.keys(exposeMethods.value).forEach(key => {
            exposed[key] = exposeMethods.value[key]
        })
        if (customMethods) {
            Object.keys(customMethods).forEach(key => {
                exposed[key] = customMethods[key]
            })
        }

    }, { deep: true })
    return { componentRef, exposed }
}